package com.elvin.platform.schedule;

import com.alibaba.fastjson.JSON;
import com.elvin.platform.beans.Device;
import com.elvin.platform.beans.Dictionary;
import com.elvin.platform.beans.Organize;
import com.elvin.platform.service.DeviceService;
import com.elvin.platform.service.DictionaryService;
import com.elvin.platform.service.OrganizeService;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Log4j2
public class ScheduledJob {

@Resource
private DeviceService service;
@Resource
private DictionaryService dictionaryService;
@Resource
private OrganizeService organizeService;

  @Async
  //@Scheduled(cron = "0 0/3 * * * ?")
  @Scheduled(cron = "0 0 23 * * ?")
  public void scheduledMethod1() {
    log.info("定时器开始scheduledMethod");
    List<Organize> organizeList = organizeService.selectList(null);
    organizeList.stream().forEach(e ->{
      Device entity = new Device();
      entity.setOrganizeId(e.getId());
      //1.根据条件获取设备信息
      //2.获取对应信息的场景id
      //3.根据场景id循环查询字典包
      List<Device> deviceList = service.selectDeviceList(entity);
      List<Dictionary> list = new ArrayList<>();
      for (Device device : deviceList) {
        List<Dictionary> dictionaries = dictionaryService.selectDictionaryList(device.getDevScenarios());
        list.addAll(dictionaries);
      }
      ArrayList<Dictionary> distinctDictionary = list.stream().collect(Collectors.collectingAndThen(
          Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Dictionary::getId))), ArrayList::new));
      for (Dictionary dictionary : distinctDictionary) {
        for (Dictionary dictionary5 : list) {
          if(dictionary.getId().equals(dictionary5.getId())){
            dictionary.setAcount(dictionary.getAcount()+1);
          }
        }
      }
      if (distinctDictionary.size()>0){
        String distinctDictionaryInfo = JSON.toJSONString(distinctDictionary);
        e.setDictionaryInfo(distinctDictionaryInfo);//存储
        organizeService.updateDictionaryInfo(e);
      }
    });
  }
}
